package com.pbase.data.http;


import com.pbase.data.http.listener.OnDataRequestListenerWithProgress;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * http请求基类
 */
public class BaseHttpApi<B extends BaseHttpServer> {
    public Class<B> service;
    private String requestTag = "";

    /**
     * 建议使用当前对应的界面class name 加上生成时的毫秒数作为tag
     * @param tag
     * @param service
     * @param <T>
     */
    public <T> BaseHttpApi(String tag,Class<B>service ) {
        this.requestTag = tag ;
        this.service = service;
    }
    /**
     * 根据泛型生成请求接口类实例，通过该实例调用接口请求
     *
     * @return 请求接口类实例
     */
    protected   B create() {
        B retrofit = RetrofitClient.getInstance(getRetrofitBuilderTool()).create(  service);
        return retrofit;
    }


    /**
     * 重写此方法以获得项目自定义的配置
     * @return Retrofit构建配置工具
     */
    protected RetrofitBuilderTool getRetrofitBuilderTool() {
        return new RetrofitBuilderTool();
    }

    protected void request(Observable observable,
                           final OnDataRequestListenerWithProgress listener){
        request(false,observable,listener);
    }
    /**
     * 请求最终层
     * @param mainThread 是否回调主线程，mvvm模式一般无需自己返回主线程控制ui
     * @param observable
     * @param listener
     */
    protected void request(boolean mainThread, Observable observable,
                           final OnDataRequestListenerWithProgress listener) {
        if (listener != null) {
            //根据界面tag存储http任务
            RequestObserverControl.getInstance().addSubscription(requestTag, listener);
        }
        if (mainThread) {
            observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(listener);
        } else {
            observable.subscribe(listener);
        }
    }
}
